#!/usr/bin/perl

=head1 NAME

lbdbsorter.pl - Sorts out lmdb database, removing duplicate info, etc

=head1 DESCRIPTION

Parses through the Little Brother Database which mutt uses for autocompletion
and removes duplicate entries and other such nonsense.

require configvars;    # Found via PERL5LIB env variable
use strict;

=head1 SYNOPSIS 
                    
  perl lbdbsorter.pl    
                          
=cut

my $infile  = $MauchConfig::lbdblog;
my $outfile = '/tmp/lbdblog.tmp';

open( INPUT,  "<" . $infile );
open( OUTPUT, ">" . $outfile );
my @lines = <INPUT>;
close INPUT;
my @sorted = sort byname @lines;
my %seen   = ();
my @uniq;

foreach my $item ( @sorted ) {
    my ( $email, $name, $date ) = split( /\t/, $item );
    $email = lc( $email );
    my $blurb = "$email\:\:\:$name";
    push( @uniq, "$blurb\t$date" ) unless ( $seen{ $blurb }++ );
}

foreach my $item ( @uniq ) {
    my ( $blurb, $date ) = split( /\t/,  $item );
    my ( $email, $name ) = split( /:::/, $blurb );
    chomp( $email, $name, $date );
    print OUTPUT "$email\t$name\t$date\n";
}
close OUTPUT;

unlink $infile;
rename( $outfile, $infile );

sub byname {
    my ( $email1, $name1, $date1 ) = split( /\t/, $a );    # What are the fields?
    my ( $email2, $name2, $date2 ) = split( /\t/, $b );    # What are the fields?
    return ( lc( $name2 ) cmp lc( $name1 ) );              # compared based on lowercase names
}

=head1 BUGS AND LIMITATIONS

No bugs have been reported.

Please report any bugs or feature requests to C<cmauch@gmail.com>

=head1 AUTHOR

Charles Mauch <cmauch@gmail.com>

=head1 LICENSE

Copyright (c) 2006 Charles Mauch

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA  02110-1301, USA.

=head1 SEE ALSO

perl(1).

=cut

# $Id$
